package cn.broadmax.boot.config;

import cn.broadmax.boot.base.model.LoginUser;
import cn.broadmax.boot.util.SpringContextUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author jeff
 * @date 2020/6/20
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MyMetaObjectHandler();
    }

    public static class MyMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

            LoginUser subject = SpringContextUtils.getSubject();
            if(subject != null){
                this.strictInsertFill(metaObject, "createUserId", String.class, subject.getId());
                this.strictInsertFill(metaObject, "updateUserId", String.class, subject.getId());
            }
            else{
                this.strictInsertFill(metaObject, "createUserId", String.class, "");
                this.strictInsertFill(metaObject, "updateUserId", String.class, "");
            }
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            LoginUser subject = SpringContextUtils.getSubject();
            if(subject != null){
                this.strictUpdateFill(metaObject, "updateUserId", String.class, subject.getId());
            }
            else{
                this.strictUpdateFill(metaObject, "updateUserId", String.class, "");
            }
        }
    }

}
